package br.com.ds3.interceptor;

import java.util.Arrays;
import java.util.Collection;

import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.ds3.annotation.Permission;
import br.com.ds3.annotation.Public;
import br.com.ds3.controller.PrincipalController;
import br.com.ds3.model.Perfil;
import br.com.ds3.session.UserSession;

@Intercepts
public class LoginInterceptor implements Interceptor {

    private Result result;
    private UserSession userSession;

    public LoginInterceptor(Result result, UserSession userSession) {
        this.result = result;
        this.userSession = userSession;
    }
    
    @Override
    public boolean accepts(ResourceMethod method) {
        return 
            !(method.getMethod().isAnnotationPresent(Public.class) ||
            method.getResource().getType().isAnnotationPresent(Public.class));
    }

    public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) {
    	
        Permission methodPermission = method.getMethod().getAnnotation(Permission.class);
        Permission controllerPermission = method.getResource().getType().getAnnotation(Permission.class);

        if (this.hasAccess(methodPermission) && this.hasAccess(controllerPermission)) {
           stack.next(method, resourceInstance);
        } else {
        	result.redirectTo(PrincipalController.class).home("Você não tem autorização para acessar essa página!");
        }    	    	
    }
    
    private boolean hasAccess(Permission permission) {
        if (permission == null) {
           return true;
        }

        Collection<Perfil> perfilList = Arrays.asList(permission.value());
        return (userSession.getUser() != null) && perfilList.contains(userSession.getUser().getPerfil());
    }    
}